package org.xin.security.component;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.xin.common.util.ClientUtil;
import org.xin.common.util.XinUtil;
import org.xin.common.util.ip.AddressUtil;
import org.xin.common.util.ip.IPUtil;
import org.xin.framework.component.CaptchaComponent;
import org.xin.framework.config.exception.CloudException;
import org.xin.framework.constant.DataStatus;
import org.xin.security.common.SecurityUtil;
import org.xin.security.common.UserConstants;
import org.xin.security.pojo.entity.SysRole;
import org.xin.security.pojo.entity.SysUser;
import org.xin.security.pojo.entity.SysUserSecurity;
import org.xin.security.service.ISysRoleService;
import org.xin.security.service.ISysUserSecurityService;
import org.xin.security.service.ISysUserService;
import org.xin.security.pojo.form.UserRegisterForm;

/**
 * @author ：xin
 * @date ：Created in 2021/10/2
 * @desc <p> 注册校验方法 </p>
 * @modified By：$
 * @version: $
 */
@Component
public class UserRegisterComponent {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysUserSecurityService userSecurityService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private CaptchaComponent captchaComponent;

    /**
     * 注册
     */
    @Transactional(rollbackFor = {Exception.class, CloudException.class})
    public Boolean register(UserRegisterForm form) {
        String msg = "", username = form.getUsername(), password = form.getPassword(), uuid = form.getUuid(), code = form.getCode();
        captchaComponent.validateCaptcha(username, code, uuid);

        if (userSecurityService.checkUserNameUnique(username)) {
            throw new CloudException("用户名已存在!");
        }
        if (userService.checkUserEmailUnique(form.getEmail())) {
            throw new CloudException("邮箱已存在!");
        }

        String userId = IdUtil.fastUUID(), roleId = "", salt = RandomUtil.randomString(8);

        try {
            SysRole sysRole = roleService.selectRoleByCode(UserConstants.DEFAULT_ROLE_CODE);
            if (XinUtil.isNull(sysRole)) {
                throw new CloudException("系统没有角色");
            }
            roleId = sysRole.getId();

            SysUser sysUser = SysUser.builder()
                    .address(AddressUtil.getRealAddressByIP(IPUtil.getIpAddr(ClientUtil.getRequest())))
                    .avatar("https://q1.qlogo.cn/g?b=qq&nk=1753047507&s=640")
                    .birth(DateUtil.now())
                    .source("账号注册")
                    .nickname(username)
                    .email(form.getEmail())
                    .id(userId)
                    .build();
            sysUser.setId(userId);

            if (!userService.save(sysUser)) {
                throw new CloudException("注册用户异常");
            }

//            String pwd = SecurityUtil.encryptPassword(password.trim() + salt);
            String pwd = XinUtil.Md5(password.trim(), salt);
            SysUserSecurity sysUserSecurity = SysUserSecurity.builder()
                    .sysUserId(userId)
                    .userStatus(String.valueOf(DataStatus.ENABLE.ordinal()))
                    .username(username)
                    .sysRoleId(roleId)
                    .salt(salt)
                    .password(pwd)
                    .build();

            if (!userSecurityService.save(sysUserSecurity)) {
                throw new CloudException("注册用户失败");
            }
        }catch (Exception e){
            throw new CloudException("注册用户异常!", e);
        }
        return true;
    }


}
